<?php
if (!defined('FosfoaSystem')) {
    exit(1);
}
class customersModel extends spModel
{
    var $pk = "customers_id"; // 每个唯一的标志，可以称为主键
    var $table = "customers"; // 数据表的名称
    var $linker = array(array(
            'type' => 'hasone', // 关联类型，这里是一对一关联
            'map' => 'detail', // 关联的标识
            'mapkey' => 'customers_id', // 本表与对应表关联的字段名
            'fclass' => 'address_bookModel', // 对应表的类名
            'fkey' => 'customers_id', // 对应表中关联的字段名
            'enabled' => true // 启用关联
                ));
    var $verifier = array( // 验证登录信息，由于密码是加密的输入框生成的，所以不需要进行“格式验证”
            "rules" => array( // 规则
                'customers_email_address' => array( // 这里是对email的验证规则
                'notnull' => true, // email不能为空
                'email' => true, // 必须要是电子邮件格式
                ), ), "messages" => array( // 提示信息
                'customers_email_address' => array(
                'notnull' => "email can not be empty!",
                'email' => "Is your email address correct?",
                ), ));

    /**
     * 新用户注册
     * 
     */
    public function create_account($data_customers, $data_address)
    {
        $password = $data_customers[customers_pass];
        $data_customers[customers_pass] = md5("fosf" . $password . "jx");
        $address = spClass("address_bookModel");

        $emailExist = $this->emailExist($data_customers['customers_email_address']);
        if ($emailExist) {
            $msg = T('User already exists!');
            $type = 'n'; //用户邮箱存在
            //dump($emailExist);
            $user = array('addressid' => $emailExist[customers_default_address_id],
                    'customersid' => $emailExist[customers_id]);
            //exit;
        } else {
            $addressid = $address->Create($data_address); //将详细地址存入地址库，并返回地址库ID
            $data_customers['customers_default_address_id'] = $addressid; //库ID给入顾客表中
            $customersid = $this->create($data_customers); //插入新的顾客数据，并返回顾客ID
            $data_address['customers_id'] = $customersid; //顾客ID给入数组中
            $data_address['customers_name'] = $data_customers['customers_firstname'] . ' ' .
                $data_customers['customers_lastname']; //顾客全称给入数组中
            $address->update('address_book_id=' . $addressid, $data_address); //修改顾客数据的默认地址ID

            $result = $this->spLinker()->find('customers_id=' . $customersid);
            $data = serialize($result);
            $sessionobj = spClass("customersSession");
            $sessionobj->write($data, time());
            $HB = $this->CartHB();
            //date_default_timezone_set('America/Toronto');
            $mail = spClass('email_templateModel');

            //1为注册成功模板
            $email_address = $data_customers['customers_email_address'];
            $fullname = $data_customers['customers_firstname'] . ' ' . $data_customers['customers_lastname'];
            $mail->send_create_account($email_address, $fullname, $password);
            $type = 'y'; //用户注册成功
            $msg = T('User created successfully!');
            $user = array('addressid' => $addressid, 'customersid' => $customersid);
            //$this->jump("create_account_success.html");
        }
        return array(
            'type' => $type,
            'msg' => $msg,
            'user' => $user);
    }


    /**
     * 这里我们建立一个成员函数来进行用户登录验证
     *
     * @param uname    用户名
     * @param upass    密码，请注意，本例中使用了加密输入框，所以这里的$upass是经过MD5加密的字符串。
     */
    public function customerslogin($customers_email_address, $customers_pass)
    {
        $conditions = array(
            'customers_email_address' => $customers_email_address,
            'customers_pass' => md5("fosf" . $customers_pass . "jx"),
            // 请注意，本例中使用了加密输入框，所以这里的$upass是经过MD5加密的字符串。
            'enabled' => 1,
            );
        // dump($conditions);
        // 检查用户名/密码，由于$conditions是数组，所以SP会自动过滤SQL攻击字符以保证数据库安全。
        if ($result = $this->find($conditions)) {
            // 成功通过验证，下面开始对用户的权限进行会话设置，最后返回用户ID
            $sessionobj = spClass("customersSession");
            $data = serialize($result);
            $sessionobj->write($data, 86000);
            //$_SESSION["customersinfo"] = $result; // 在SESSION中记录当前用户的信息
            //ini_set("session.gc_maxlifetime", "18000");
            //登入成功上传登入时间和登入记录
            $condition = array('customers_id' => $result['customers_id']);
            $data = array('customers_lastlogin' => time());
            $this->update($condition, $data);
            //最后返回真
            return true;
        } else {
            // 找不到匹配记录，用户名或密码错误，返回false
            return false;
        }
    }
    /**
     * 切换客户为上线状态
     *
     * @param 用户EMAIL
     */
    public function loingok($email_address)
    {
        $data = $this->find(array('customers_email_address' => $email_address));
        if ($data) {
            // 成功通过验证，下面开始对用户的权限进行会话设置，最后返回用户ID
            $sessionobj = spClass("customersSession");
            $data = serialize($data);
            $sessionobj->write($data, 86000);
            //$_SESSION["customersinfo"] = $result; // 在SESSION中记录当前用户的信息
            //ini_set("session.gc_maxlifetime", "18000");
            //登入成功上传登入时间和登入记录
            $condition = array('customers_id' => $result['customers_id']);
            $data = array('customers_lastlogin' => time());
            $this->update($condition, $data);
            //最后返回真
            return true;
        } else {
            // 找不到匹配记录，用户名或密码错误，返回false
            return false;
        }
    }

    /**
     * 修改密码 
     */
    public function editpass($customers_id, $oldpass, $newpass)
    {
        $conditions = array(
            'customers_id' => $customers_id,
            'customers_pass' => md5("fosf" . $oldpass . "jx"), // 请注意，本例中使用了加密输入框，所以这里的$upass是经过MD5加密的字符串。
            'enabled' => 1,
            );
        if ($result = $this->find($conditions)) {
            $condition = array('customers_id' => $result['customers_id']);
            $data = array('customers_pass' => md5("fosf" . $newpass . "jx"));
            $this->update($condition, $data);
            return true;
        }
        return false;
    }

    /**
     * 邮件修改密码 
     */
    public function editmailpass($mail, $newpass)
    {
        $conditions = array(
            'customers_email_address' => $mail,
            'enabled' => 1,
            );
        if ($result = $this->find($conditions)) {
            //dump($result);
            //echo md5("fosf".$newpass."jx");

            //exit;
            $condition = array('customers_id' => $result['customers_id']);
            $data = array('customers_pass' => md5("fosf" . $newpass . "jx"));
            $this->update($condition, $data);
            return true;
        }
        return false;
    }


    /**
     * 无权限提示及跳转
     */
    public function acljump($url = '')
    {
        // 这里直接“借用”了spController.php的代码来进行无权限提示
        if ($url == '') {
            $url = spUrl("user", "login");
        }

        $scriptName = $_SERVER["REQUEST_URI"];
        echo "<html><head>";
        echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">";
        //echo "<meta http-equiv='refresh' content='5;url={$url}'>";
        echo "<title>" . T('Permission denied!') . "</title>";
        echo "</head><body>" . T('Permission denied!') . $scriptName . "<a href='{$url}'>请重新登入</a></body></html>";
        exit;
    }

    /**
     *
     * 成功提示程序
     *
     * 应用程序的控制器类可以覆盖该函数以使用自定义的成功提示
     *
     * @param $msg   成功提示需要的相关信息
     * @param $url   跳转地址
     */
    public function success($msg, $url)
    {
        echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><script>function sptips(){document.write(\"{$msg}\");location.href=\"{$url}\";}</script></head><body onload=\"sptips()\"></body></html>";
        exit;
    }

    public function Detail($customers_id)
    {
        $condition = array('customers_id' => $customers_id);
        $arr = $this->find($condition);
        return $arr;
    }


    public function userExist($username, $uid)
    {
        $userExist = $this->find(array('uname' => $username));
        if ($userExist == null) {
            return false;
        }
        if ($userExist['uid'] == $uid) {
            return false;
        }
        return true;
    }

    public function emailExist($email)
    {
        $userExist = $this->find(array('customers_email_address' => $email));
        //dump($userExist);
        if ($userExist == null) {

            return false;
        }
        if ($userExist['customers_email_address'] == $email) {
            return $userExist;
        }
        return true;
    }
    /**
     * 合并购物车，并返回合并状态
     * 返回真假,True 有记录，且合并了，False 无记录不需合并
     */
    public function CartHB()
    {
        $customers_basketModel = spClass('customers_basketModel');
        $customers = spClass('customersSession')->read();
        $customers = unserialize($customers);
        //echo $customers['customers_id'];
        //dump($customers);
        // 成功登录，跳转。这里要进行判断一下：
        $cart = spClass("CartAPI");
        $tmpArray = array();
        $tmpArray = $cart->CartViewold(); // 防止在此之前数据被外部修改
        // price1 是产品1的总价格
        // price2 是产品2的总价格
        // price3 是产品3的总价格
        // count  是产品的总数量

        $i = 0;
        if (is_array($tmpArray['id'])) //判断临时购物车是否有商品，如有就合并客户的永久购物车
            {
            $conditions = array('customers_id' => $customers['customers_id']);
            $customers_basket = $customers_basketModel->findCount($conditions);
            foreach ($tmpArray['id'] as $key => $val) {

                //去除相同产品并且尺码一样的产品不用合并
                //if(!spClass('customers_basketModel')->basketExist($customers['customers_id'],$tmpArray['pid'][$key],$tmpArray['size'][$key]))
                //{
                $data = array(
                    'customers_id' => $customers['customers_id'],
                    'products_id' => $tmpArray['pid'][$key],
                    'products_name' => $tmpArray['name'][$key],
                    'customers_basket_quantity' => $tmpArray['count'][$key],
                    'attributes' => $tmpArray['size'][$key],
                    'final_price' => $tmpArray['price1'][$key],
                    'discounted_price' => $tmpArray['price2'][$key],
                    'customers_basket_date_added' => TIME());
                $customers_basketModel->create($data);
                //}
                $i++;
            }
            //合并完就清空临时购物车
            spClass('cartSession')->del(); //清除临时旧购物车
            if ($customers_basket > 0) {
                $HB = true;
            } else {
                $HB = false;
            }
        } else {
            $HB = false;
        }
        $_SESSION['HB'] = $HB;
        return $HB;
    }
    /**
     * 如果在线就获取当前登入状态信息
     */
    function online()
    {
        if (isset($_COOKIE['abcsession_id'])) {
            $customers = spClass('customersSession')->read(); //从SEESSION表中获取当前用户信息
            $customers = unserialize($customers); //反序例化
            return $customers;
        }
        return;
    }
}